package main

import (
	"github.com/globalsign/mgo/bson"
	"time"
)

type Favorite struct {
	ID              bson.ObjectId `bson:"_id" json:"_id"`
	Title            string        `bson:"title" json:"title"`
	ToutiaoUrl         string        `bson:"toutiao_url" json:"toutiao_url"`
	OrigUrl          string        `bson:"orig_url" json:"orig_url"`
	CreatedAt       time.Time     `bson:"created_at" json:"created_at"`
	UpdatedAt       time.Time     `bson:"updated_at" json:"updated_at"`
}

//Insert docs
func (db *StarDb) Insert(collection string, docs ...interface{}) error {
	s := db.Sess.Copy()
	defer s.Close()
	c := s.DB(db.Option.DbName).C(collection)
	err := c.Insert(docs...)
	return err
}

//FindByName find doc by name
func (db *StarDb) FindByTitle(collection string, title string) (*Favorite, error) {
	var restult Favorite
	s := db.Sess.Copy()
	defer s.Close()
	c := s.DB(db.Option.DbName).C(collection)
	err := c.Find(bson.M{"title": title}).One(&restult)
	return &restult, err
}

//FindByName find doc by url
func (db *StarDb) FindByFullName(collection string, fullName string) (*Favorite, error) {
	var restult Favorite
	s := db.Sess.Copy()
	defer s.Close()
	c := s.DB(db.Option.DbName).C(collection)
	err := c.Find(bson.M{"full_name": fullName}).One(&restult)
	return &restult, err
}

func (db *StarDb) CountTotal(collection string) (int, error) {
	s := db.Sess.Copy()
	defer s.Close()
	c := s.DB(db.Option.DbName).C(collection)
	n, err := c.Count()
	return n, err
}

func (db *StarDb) Find(collection string, query interface{}, skip, limit int) (*[]Favorite, error) {
	var restult []Favorite
	s := db.Sess.Copy()
	defer s.Close()
	c := s.DB(db.Option.DbName).C(collection)
	err := c.Find(query).
		Sort("_id").
		Skip(skip).
		Limit(limit).
		All(&restult)
	return &restult, err
}